package com.xl.exp.session;

import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;

import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

@Slf4j
public class SysSessionManager extends DefaultWebSessionManager {

    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {

        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if(sessionKey instanceof WebSessionKey){
            request = ((WebSessionKey)sessionKey).getServletRequest();
        }
        if(request != null && sessionId != null){

            Session session = (Session) request.getAttribute(sessionId.toString());

            if (session != null){
                log.debug("request 中的session");
                return session;
            }
        }
        log.debug(" 从 request 中获取缓存失败");
        Session session = super.retrieveSession(sessionKey);

        if(request != null && sessionId != null){
            request.setAttribute(sessionId.toString(),session);
        }

        return session;
    }
}
